//
//  WebViewController.m
//  DL-TalkOrderApp
//
//  Created by 杨开 on 16/9/14.
//  Copyright © 2016年 顶呱呱-ios l. All rights reserved.
//

#import "DLWebsViewController.h"
#import "WebBgView.h"
#import <Masonry/Masonry.h>
#import <MJRefresh/MJRefresh.h>

@interface DLWebsViewController ()

@property (nonatomic,copy)WVJBResponseCallback locationBlock;

@end

@implementation DLWebsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.isHaveTitle) {
       self.navigationItem.title = @"正在加载";
    }
    if (@available(iOS 11.0, *)) {

    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
-(void)dgg_addNavItems
{
    if (self.isShare) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"浏览器" style:(UIBarButtonItemStylePlain) target:self action:@selector(share)];
        
    }
    if (self.isDownload) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下载" style:(UIBarButtonItemStylePlain) target:self action:@selector(download)];
    }
    if (self.isHaveRightButton){
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.rightButtonName style:(UIBarButtonItemStylePlain) target:self action:@selector(rightButtonClick)];
    }
}

- (void)rightButtonClick{
    if(self.rightButtonBlock){
        self.rightButtonBlock();
    }
}

- (void)download {
    if (self.downloadBlock) {
        self.downloadBlock();
    }
}

-(void)share
{
    [self showSystemAlertWithTitle:@"是否在Safari中打开" msg:nil buttons:@[@"取消",@"打开"] block:^(NSInteger index) {
        if (index == 1) {
            NSString *str = @"";
            if ([NSString isEmpty:self.webView.URL.absoluteString]) {
                str = self.urlstr;
            }else
            {
                str = self.webView.URL.absoluteString;
            }
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:str]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            }else
            {
                [self showSystemAlertWithTitle:@"错误的链接，无法打开" msg:nil buttons:nil block:nil];
            }
        }
    }];
}

-(void)dgg_addSubviews
{
    [self initWebView];
}

-(void)dgg_layoutNavigation
{
    if (!self.navigationController.navigationBar.hidden &&self.navigationController.viewControllers.count>1) {
        [self additem];
    }
}

- (void)additem{
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSString *leftButtonImageName = @"DLUIKit_Nav_Return";
    [backButton setImage:self.leftBackImg ? self.leftBackImg : [UIImage imageNamed:leftButtonImageName] forState:(UIControlStateNormal)];
    [backButton setImage:self.leftBackImg ? self.leftBackImg : [UIImage imageNamed:leftButtonImageName] forState:(UIControlStateHighlighted)];
    [backButton setTitle:@"" forState:(UIControlStateNormal)];
    [backButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [backButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateHighlighted)];
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0);
    [backButton sizeToFit];
      backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
     backButton.bounds = CGRectMake(0, 0, kBarHeight, kBarHeight);
    UIBarButtonItem *item1 =[[UIBarButtonItem alloc] initWithCustomView:backButton];
    if ([self.webView canGoBack]) {
        [backButton addTarget:self action:@selector(goBack) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        UIButton *backButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton2 setTitle:@"关闭" forState:(UIControlStateNormal)];
        [backButton2 setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [backButton2 setTitleColor:[UIColor whiteColor] forState:(UIControlStateHighlighted)];
        backButton2.contentEdgeInsets = UIEdgeInsetsMake(0, -18, 0, 0);
        [backButton2 sizeToFit];
        backButton2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        backButton2.bounds = CGRectMake(0, 0, kBarHeight, kBarHeight);
         [backButton2 addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
        UIBarButtonItem *item2 =[[UIBarButtonItem alloc] initWithCustomView:backButton2];
       
        
        self.navigationItem.leftBarButtonItems = @[item1,item2];
    }else
    {
        [backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
        self.navigationItem.leftBarButtonItems = @[item1];
    }
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)goBack
{
    [self.webView goBack];
}
#pragma mark - 初始化 WKWebView
-(void)initWebView{
    
    _aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _aiv.color =[UIColor grayColor];
    
//    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
//    config.preferences = [[WKPreferences alloc]init];
//    config.allowsInlineMediaPlayback = YES;
//    config.selectionGranularity = YES;
//    //自定义配置，一般用于js调用oc方法(OC拦截URL中的数据做自定义操作)
//    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
//
//    [userContentController addScriptMessageHandler:self name:@"start"];
//    config.userContentController = userContentController;
//    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0,0,0,0) configuration:config];
    
    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0,0,0,0)];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.backgroundColor =[DLThemeAdapter backgroundColor];
    _webView.scrollView.showsVerticalScrollIndicator =NO;
    _webView.opaque = NO;
    _webView.allowsBackForwardNavigationGestures = YES;
    _webView.clipsToBounds = YES;
    _webView.scrollView.showsHorizontalScrollIndicator =NO;
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:_webView];
   
     kself
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view).with.insets(UIEdgeInsetsMake(self.isHideNav ? 0 : kNavHeight, 0, 0, 0));
        
    }];
    self.view.backgroundColor = [UIColor whiteColor];

    [WKWebViewJavascriptBridge enableLogging];
    //_bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
    //[_bridge setWebViewDelegate:self];
    if (self.jsBridgeRegisteredBlock) {
        self.jsBridgeRegisteredBlock();
    }
  
    [self.view addSubview:_aiv];
    [_aiv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakSelf.webView);
    }];
    _webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf.webView reload];
        
    }];
    
    [self loadWebView];

//    self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
//    [self.bridge registerHandler:@"ObjC Echo" handler:^(id data, WVJBResponseCallback responseCallback) {
//        NSLog(@"ObjC Echo called with: %@", data);
//        responseCallback(data);
//    }];
//    [self.bridge callHandler:@"JS Echo" data:nil responseCallback:^(id responseData) {
//        NSLog(@"ObjC received response: %@", responseData);
//    }];
    
}
#pragma mark - 加载 WKWebView
-(void)loadWebView{
    
    //    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"html"];
    //    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    //    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    //    [_webView loadHTMLString:appHtml baseURL:baseURL];
    if ([NSString isEmpty:_urlstr]) {
        _urlstr = @"https://www.baidu.com";
    }
    if([_urlstr hasPrefix:@"http"] || [_urlstr hasPrefix:@"https"]){
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlstr]]];
           NSLog(@"%@",[NSURL URLWithString:_urlstr]);
    }else{
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:_urlstr]]];
           NSLog(@"%@",[NSURL fileURLWithPath:_urlstr]);
    }
}


#pragma mark - WKNavigationDelegate

/**
 *  页面开始加载时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
    NSLog(@"页面开始加载时调用")
    [_aiv startAnimating];
}
/**
 *  当内容开始返回时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"当内容开始返回时调用")
}
/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"页面加载完成之后调用")
    NSLog(@"网页标题%@",webView.title);
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:webView.title]) {
            self.navigationItem.title = self.emptyTitle;
        }else
        {
            self.navigationItem.title = webView.title;
        }
        if (self.isSetTitleLength && self.navigationItem.title.length > 10) {
            NSString *titleStr = self.navigationItem.title;
            self.navigationItem.title = [[titleStr substringToIndex:10] stringByAppendingString:@"..."];
        }
    }
    
    [_aiv stopAnimating];
    if (_webView.scrollView.mj_header) {
          [_webView.scrollView.mj_header endRefreshing];
    }
  
      [self additem];
}
/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(nonnull NSError *)error
{
    
    NSLog(@"页面加载失败时调用")
    NSLog(@"........error======= %@",error);
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:webView.title]) {
            self.navigationItem.title = self.emptyTitle;
        }else
        {
           self.navigationItem.title = webView.title;
        }
        
    }
    if([error code] == NSURLErrorCancelled)
    {
        return;
    }
    [_aiv stopAnimating];
    if (_webView.scrollView.mj_header) {
        [_webView.scrollView.mj_header endRefreshing];
    }
    NSString *title = @"";
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:webView.title]) {
            title = self.emptyTitle;
        }else
        {
            title = webView.title;
        }
    }
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:webView.title]) {
            self.navigationItem.title = self.emptyTitle;
        }else
        {
            self.navigationItem.title = webView.title;
        }
    }
  
    BOOL isShowNavBar = NO;
    
    if (self.navigationController &&self.navigationController.viewControllers.count==1) {
        isShowNavBar = YES;
    }else if (self.navigationController.navigationBar.hidden)
    {
        isShowNavBar = YES;
    }else if (!self.navigationController)
    {
        isShowNavBar = YES;
    }
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:title]) {
            self.navigationItem.title = title;
        }
 }
   
    
    kself
    [WebBgView loadNibWithTitle:title isShowNavBar:isShowNavBar tapBlock:^{
        if (weakSelf.webView.canGoBack == YES) {
            [weakSelf.webView reload];
        }else
        {
            [weakSelf loadWebView];
        }
    } popBlock:^{
        if (weakSelf.webView.canGoBack == YES) {
            [weakSelf.webView goBack];
        }else
        {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }
        
        
    } subView:webView];
    
     [self additem];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    if (!self.isHaveTitle) {
        if ([NSString isEmpty:webView.title]) {
            self.navigationItem.title = self.emptyTitle;
        }else
        {
            self.navigationItem.title = webView.title;
        }
    }
    [_aiv stopAnimating];
    if (_webView.scrollView.mj_header) {
        [_webView.scrollView.mj_header endRefreshing];
    }
     [self additem];
    if([error code] == NSURLErrorCancelled){
        
        return;
    }
    
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"接收到服务器跳转请求之后调用")
}
/**
 *  在收到响应后，决定是否跳转
 *
 *  @param webView            实现该代理的webview
 *  @param navigationResponse 当前navigation
 *  @param decisionHandler    是否跳转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    // 允许跳转
    
    decisionHandler(WKNavigationResponsePolicyAllow);
    
    // 不允许跳转
    // decisionHandler(WKNavigationResponsePolicyCancel);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    if(webView != self.webView) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    UIApplication *app = [UIApplication sharedApplication];
    if ([navigationAction.request.URL.scheme isEqualToString:@"tel"])
    {
        if ([app canOpenURL:navigationAction.request.URL])
        {
            [app openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }else if ([navigationAction.request.URL.absoluteString containsString:@"itunes.apple.com"])
    {
        if ([app canOpenURL:navigationAction.request.URL])
        {
            [app openURL:navigationAction.request.URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }else
    {
        
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSString *msg = [NSString isEmpty:message] ? @"" : message;
    [self showSystemAlertWithTitle:@"提示" msg:msg buttons:@[@"确认"] block:^(NSInteger index) {

    }];
    
//    [TipTool showSystemAlertWithTitle:@"提示" msg:[Helper isEmpty:message]?@"":message buttons:@[@"确认"] block:^(NSInteger index) {
//        //completionHandler();
//    }];
    //bugly问题修复2018-12-03，系统弹窗显示之后，进入后台一段时间再进入前台，系统弹窗被释放，没有回调导致WKWebview崩溃
    completionHandler();
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    [self showSystemAlertWithTitle:@"提示" msg:[NSString isEmpty:message]?@"":message buttons:@[@"取消",@"确认"] block:^(NSInteger index) {
        if (index == 0) {
            completionHandler(NO);
        }else
        {
            completionHandler(YES);
        }
    }];
    
    
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    
     __weak typeof (alertController) weakAlertController =alertController;
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(weakAlertController.textFields[0].text?:@"");
    }])];
}
-(void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
        
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (_webView.scrollView.mj_header) {
        [_webView.scrollView.mj_header endRefreshing];
    }
    NSLog(@"内存警告%@", [self class]);
    
}


-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
    self.webView = nil;
    self.urlstr = nil;
}

- (void)showSystemAlertWithTitle:(NSString *)title msg:(NSString *)msg buttons:(NSArray *)buttons block:(void(^)(NSInteger index))block{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:(UIAlertControllerStyleAlert)];
    for (int i = 0; i<buttons.count; i++) {
        NSString *btnText = buttons[i];
        NSInteger type = UIAlertActionStyleDefault;
        if ([btnText isEqualToString:@"取消"]) {
            type = UIAlertActionStyleDestructive;
        }else if ([btnText isEqualToString:@"删除"]){
            type = UIAlertActionStyleDestructive;
        }
        UIAlertAction *alert = [UIAlertAction actionWithTitle:btnText style:type handler:^(UIAlertAction * _Nonnull action) {
            if (block) {
                block(i);
            }
        }];
        [alertVC addAction:alert];
    }
    
    UIWindow *window =[UIApplication sharedApplication].delegate.window;
    if (window.rootViewController.presentedViewController) {
        [window.rootViewController.presentedViewController presentViewController:alertVC animated:YES completion:nil];
    }else{
        [window.rootViewController presentViewController:alertVC animated:YES completion:nil];
    }
}


@end
